import { t } from 'i18next'
import { useEffect } from 'react'
import shallow from 'zustand/shallow'
import { ListTranslator } from './translator'
import { Alert } from '@/components/Alert'
import { findIndex } from 'lodash-es'
import { useSmsStore } from './store'
import { differenceBy } from 'lodash-es'
import { ListTopActionItem } from '@/components/List'
import { MtEntity } from '@/api/manager/mt'
import { DropData } from '@/api/manager/type'

export const useData = () => {
	const { list, model, update, fetchSmsList } = useSmsStore(
		(state) => ({
			list: state.list,
			model: state.model,
			update: state.update,
			fetchSmsList: state.fetchSmsList,
		}),
		shallow
	)
	useEffect(() => {
		fetchSmsList()
	}, [])
	useEffect(() => {
		if (model === 3) {
			update({ speed: 1, showSpeedAndroll: false })
		} else {
			update({ showSpeedAndroll: true })
		}
	}, [model])
	//验证滚动次数
	const validateRollTime = (v: string) => {
		v = v.replace(/[^\d]/g, '')
		let _v
		if (254 < Number(v)) {
			_v = 254
		} else {
			_v = Number(v)
		}
		update({ rollTime: _v })
	}
	//拖拽
	const handleDrop = (dataTransfer: DropData, index: number) => {
		if (dataTransfer && dataTransfer.data && dataTransfer.data.mt) {
			let mt = dataTransfer.data.mt
			let isMt = mt.isMt
			if (!isMt) {
				Alert(t('会议不能进入接收终端列表'))
				return
			}
			// 添加列表
			let mts = ListTranslator([mt as MtEntity])
			if (dataTransfer.from !== 'sms') {
				const insertList = differenceBy(mts, list, (x) => x.mtKey)
				let newList = [...list.slice(0, index), ...insertList, ...list.slice(index)]
				update({ list: newList })
			} else {
				const baseList = differenceBy(list, mts, (x) => x.mtKey)
				let insertToBaseIndex = index
				const baseListMtKeys = baseList.map((l) => l.mtKey)
				const nextFirstBaseListIndex = findIndex(list, (l) => baseListMtKeys.includes(l.mtKey), index)
				if (nextFirstBaseListIndex === -1) {
					insertToBaseIndex = baseList.length
				} else {
					insertToBaseIndex = baseList.findIndex((l) => l.mtKey === list[nextFirstBaseListIndex].mtKey)
				}
				update({
					list: [...baseList.slice(0, insertToBaseIndex), ...mts, ...baseList.slice(insertToBaseIndex)],
				})
			}
		}
	}
	const topActions: ListTopActionItem[] = [
		{
			text: t('删除'),
			onClick: () => {
				const unCheckedList = list.filter((l) => !l.status.checked)
				update({ list: unCheckedList })
			},
		},
		{
			text: t('清空'),
			onClick: () => {
				update({ list: [], _start: '' })
			},
		},
	]
	return {
		validateRollTime,
		handleDrop,
		topActions,
	}
}
